← Index
NYTProf Performance Profile   
For split.pl
  Run on Thu Apr 20 02:05:47 2023
Reported on Thu Apr 20 18:31:09 2023

Filename(eval 13)[/home/hejohns/perl5/lib/perl5/JSON.pm:295]
StatementsExecuted 28 statements in 351µs
Eval Invoked At/home/hejohns/perl5/lib/perl5/JSON.pm line 295
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
11141µs45µsJSON::Backend::XS::::initJSON::Backend::XS::init
1118µs14µsJSON::Backend::XS::::BEGIN@13JSON::Backend::XS::BEGIN@13
1115µs9µsJSON::Backend::XS::::BEGIN@51JSON::Backend::XS::BEGIN@51
0000s0sJSON::Backend::XS::::__ANON__[:36]JSON::Backend::XS::__ANON__[:36]
0000s0sJSON::Backend::XS::::__ANON__[:66]JSON::Backend::XS::__ANON__[:66]
0000s0sJSON::Backend::XS::::is_ppJSON::Backend::XS::is_pp
0000s0sJSON::Backend::XS::::is_xsJSON::Backend::XS::is_xs
0000s0sJSON::Backend::XS::::support_by_ppJSON::Backend::XS::support_by_pp
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1
2
3#
4# Helper classes for Backend Module (XS)
5#
6
7package JSON::Backend::XS;
8
9
# spent 45µs (41+4) within JSON::Backend::XS::init which was called: # once (41µs+4µs) by JSON::_load_xs at line 296 of JSON.pm
sub init {
101500ns my ($class, $module) = @_;
11
1212µs local $^W;
132177µs221µs
# spent 14µs (8+6) within JSON::Backend::XS::BEGIN@13 which was called: # once (8µs+6µs) by JSON::_load_xs at line 13
no strict qw(refs);
# spent 14µs making 1 call to JSON::Backend::XS::BEGIN@13 # spent 6µs making 1 call to strict::unimport
1413µs *{"JSON::decode_json"} = \&{"$module\::decode_json"};
151900ns *{"JSON::encode_json"} = \&{"$module\::encode_json"};
1611µs *{"JSON::is_bool"} = \&{"$module\::is_bool"};
17
181600ns $JSON::true = ${"$module\::true"};
191500ns $JSON::false = ${"$module\::false"};
20
2113µs push @JSON::Backend::XS::ISA, $module;
2214µs push @JSON::ISA, $class;
231100ns $JSON::Backend = $class;
241200ns $JSON::BackendModule = $module;
2517µs13µs ${"$class\::VERSION"} = $module->VERSION;
# spent 3µs making 1 call to UNIVERSAL::VERSION
26
2716µs1900ns if ( $module->VERSION < 3 ) {
# spent 900ns making 1 call to UNIVERSAL::VERSION
28 eval 'package JSON::PP::Boolean';
29 push @{"$module\::Boolean::ISA"}, qw(JSON::PP::Boolean);
30 }
31
321400ns for my $method (@PPOnlyMethods) {
33 *{"JSON::$method"} = sub {
34 Carp::carp("$method is not supported by $module.");
35 $_[0];
36815µs };
37 }
38
3912µs return 1;
40}
41
42sub is_xs { 1 };
43sub is_pp { 0 };
44
45sub support_by_pp {
46 my ($class, @methods) = @_;
47
48 JSON::__load_pp('JSON::PP');
49
50 local $^W;
512126µs212µs
# spent 9µs (5+3) within JSON::Backend::XS::BEGIN@51 which was called: # once (5µs+3µs) by JSON::_load_xs at line 51
no strict qw(refs);
# spent 9µs making 1 call to JSON::Backend::XS::BEGIN@51 # spent 3µs making 1 call to strict::unimport
52
53 for my $method (@methods) {
54 my $pp_method = JSON::PP->can($method) or next;
55 *{"JSON::$method"} = sub {
56 if (!$_[0]->isa('JSON::PP')) {
57 my $xs_self = $_[0];
58 my $pp_self = JSON::PP->new;
59 for (@Properties) {
60 my $getter = "get_$_";
61 $pp_self->$_($xs_self->$getter);
62 }
63 $_[0] = $pp_self;
64 }
65 $pp_method->(@_);
66 };
67 }
68
69 $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
70}
71
7212µs1;
73__END__
74
75=head1 NAME
76
77JSON - JSON (JavaScript Object Notation) encoder/decoder
78
79=head1 SYNOPSIS
80
81 use JSON; # imports encode_json, decode_json, to_json and from_json.
82
83 # simple and fast interfaces (expect/generate UTF-8)
84
85 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
86 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
87
88 # OO-interface
89
90 $json = JSON->new->allow_nonref;
91
92 $json_text = $json->encode( $perl_scalar );
93 $perl_scalar = $json->decode( $json_text );
94
95 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
96
97=head1 DESCRIPTION
98
99This module is a thin wrapper for L<JSON::XS>-compatible modules with a few
100additional features. All the backend modules convert a Perl data structure
101to a JSON text and vice versa. This module uses L<JSON::XS> by default,
102and when JSON::XS is not available, falls back on L<JSON::PP>, which is
103in the Perl core since 5.14. If JSON::PP is not available either, this
104module then falls back on JSON::backportPP (which is actually JSON::PP
105in a different .pm file) bundled in the same distribution as this module.
106You can also explicitly specify to use L<Cpanel::JSON::XS>, a fork of
107JSON::XS by Reini Urban.
108
109All these backend modules have slight incompatibilities between them,
110including extra features that other modules don't support, but as long as you
111use only common features (most important ones are described below), migration
112from backend to backend should be reasonably easy. For details, see each
113backend module you use.
114
115=head1 CHOOSING BACKEND
116
117This module respects an environmental variable called C<PERL_JSON_BACKEND>
118when it decides a backend module to use. If this environmental variable is
119not set, it tries to load JSON::XS, and if JSON::XS is not available, it
120falls back on JSON::PP, and then JSON::backportPP if JSON::PP is not available
121either.
122
123If you always don't want it to fall back on pure perl modules, set the
124variable like this (C<export> may be C<setenv>, C<set> and the likes,
125depending on your environment):
126
127 > export PERL_JSON_BACKEND=JSON::XS
128
129If you prefer Cpanel::JSON::XS to JSON::XS, then:
130
131 > export PERL_JSON_BACKEND=Cpanel::JSON::XS,JSON::XS,JSON::PP
132
133You may also want to set this variable at the top of your test files, in order
134not to be bothered with incompatibilities between backends (you need to wrap
135this in C<BEGIN>, and set before actually C<use>-ing JSON module, as it decides
136its backend as soon as it's loaded):
137
138 BEGIN { $ENV{PERL_JSON_BACKEND}='JSON::backportPP'; }
139 use JSON;
140
141=head1 USING OPTIONAL FEATURES
142
143There are a few options you can set when you C<use> this module.
144These historical options are only kept for backward compatibility,
145and should not be used in a new application.
146
147=over
148
149=item -support_by_pp
150
151 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
152
153 use JSON -support_by_pp;
154
155 my $json = JSON->new;
156 # escape_slash is for JSON::PP only.
157 $json->allow_nonref->escape_slash->encode("/");
158
159With this option, this module loads its pure perl backend along with
160its XS backend (if available), and lets the XS backend to watch if you set
161a flag only JSON::PP supports. When you do, the internal JSON::XS object
162is replaced with a newly created JSON::PP object with the setting copied
163from the XS object, so that you can use JSON::PP flags (and its slower
164C<decode>/C<encode> methods) from then on. In other words, this is not
165something that allows you to hook JSON::XS to change its behavior while
166keeping its speed. JSON::XS and JSON::PP objects are quite different
167(JSON::XS object is a blessed scalar reference, while JSON::PP object is
168a blessed hash reference), and can't share their internals.
169
170To avoid needless overhead (by copying settings), you are advised not
171to use this option and just to use JSON::PP explicitly when you need
172JSON::PP features.
173
174=item -convert_blessed_universally
175
176 use JSON -convert_blessed_universally;
177
178 my $json = JSON->new->allow_nonref->convert_blessed;
179 my $object = bless {foo => 'bar'}, 'Foo';
180 $json->encode($object); # => {"foo":"bar"}
181
182JSON::XS-compatible backend modules don't encode blessed objects by
183default (except for their boolean values, which are typically blessed
184JSON::PP::Boolean objects). If you need to encode a data structure
185that may contain objects, you usually need to look into the structure
186and replace objects with alternative non-blessed values, or enable
187C<convert_blessed> and provide a C<TO_JSON> method for each object's
188(base) class that may be found in the structure, in order to let the
189methods replace the objects with whatever scalar values the methods
190return.
191
192If you need to serialise data structures that may contain arbitrary
193objects, it's probably better to use other serialisers (such as
194L<Sereal> or L<Storable> for example), but if you do want to use
195this module for that purpose, C<-convert_blessed_universally> option
196may help, which tweaks C<encode> method of the backend to install
197C<UNIVERSAL::TO_JSON> method (locally) before encoding, so that
198all the objects that don't have their own C<TO_JSON> method can
199fall back on the method in the C<UNIVERSAL> namespace. Note that you
200still need to enable C<convert_blessed> flag to actually encode
201objects in a data structure, and C<UNIVERSAL::TO_JSON> method
202installed by this option only converts blessed hash/array references
203into their unblessed clone (including private keys/values that are
204not supposed to be exposed). Other blessed references will be
205converted into null.
206
207This feature is experimental and may be removed in the future.
208
209=item -no_export
210
211When you don't want to import functional interfaces from a module, you
212usually supply C<()> to its C<use> statement.
213
214 use JSON (); # no functional interfaces
215
216If you don't want to import functional interfaces, but you also want to
217use any of the above options, add C<-no_export> to the option list.
218
219 # no functional interfaces, while JSON::PP support is enabled.
220 use JSON -support_by_pp, -no_export;
221
222=back
223
224=head1 FUNCTIONAL INTERFACE
225
226This section is taken from JSON::XS. C<encode_json> and C<decode_json>
227are exported by default.
228
229This module also exports C<to_json> and C<from_json> for backward
230compatibility. These are slower, and may expect/generate different stuff
231from what C<encode_json> and C<decode_json> do, depending on their
232options. It's better just to use Object-Oriented interfaces than using
233these two functions.
234
235=head2 encode_json
236
237 $json_text = encode_json $perl_scalar
238
239Converts the given Perl data structure to a UTF-8 encoded, binary string
240(that is, the string contains octets only). Croaks on error.
241
242This function call is functionally identical to:
243
244 $json_text = JSON->new->utf8->encode($perl_scalar)
245
246Except being faster.
247
248=head2 decode_json
249
250 $perl_scalar = decode_json $json_text
251
252The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
253to parse that as an UTF-8 encoded JSON text, returning the resulting
254reference. Croaks on error.
255
256This function call is functionally identical to:
257
258 $perl_scalar = JSON->new->utf8->decode($json_text)
259
260Except being faster.
261
262=head2 to_json
263
264 $json_text = to_json($perl_scalar[, $optional_hashref])
265
266Converts the given Perl data structure to a Unicode string by default.
267Croaks on error.
268
269Basically, this function call is functionally identical to:
270
271 $json_text = JSON->new->encode($perl_scalar)
272
273Except being slower.
274
275You can pass an optional hash reference to modify its behavior, but
276that may change what C<to_json> expects/generates (see
277C<ENCODING/CODESET FLAG NOTES> for details).
278
279 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
280 # => JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
281
282=head2 from_json
283
284 $perl_scalar = from_json($json_text[, $optional_hashref])
285
286The opposite of C<to_json>: expects a Unicode string and tries
287to parse it, returning the resulting reference. Croaks on error.
288
289Basically, this function call is functionally identical to:
290
291 $perl_scalar = JSON->new->decode($json_text)
292
293You can pass an optional hash reference to modify its behavior, but
294that may change what C<from_json> expects/generates (see
295C<ENCODING/CODESET FLAG NOTES> for details).
296
297 $perl_scalar = from_json($json_text, {utf8 => 1})
298 # => JSON->new->utf8(1)->decode($json_text)
299
300=head2 JSON::is_bool
301
302 $is_boolean = JSON::is_bool($scalar)
303
304Returns true if the passed scalar represents either JSON::true or
305JSON::false, two constants that act like C<1> and C<0> respectively
306and are also used to represent JSON C<true> and C<false> in Perl strings.
307
308See L<MAPPING>, below, for more information on how JSON values are mapped to
309Perl.
310
311=head1 COMMON OBJECT-ORIENTED INTERFACE
312
313This section is also taken from JSON::XS.
314
315The object oriented interface lets you configure your own encoding or
316decoding style, within the limits of supported formats.
317
318=head2 new
319
320 $json = JSON->new
321
322Creates a new JSON::XS-compatible backend object that can be used to de/encode JSON
323strings. All boolean flags described below are by default I<disabled>
324(with the exception of C<allow_nonref>, which defaults to I<enabled> since
325version C<4.0>).
326
327The mutators for flags all return the backend object again and thus calls can
328be chained:
329
330 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
331 => {"a": [1, 2]}
332
333=head2 ascii
334
335 $json = $json->ascii([$enable])
336
337 $enabled = $json->get_ascii
338
339If C<$enable> is true (or missing), then the C<encode> method will not
340generate characters outside the code range C<0..127> (which is ASCII). Any
341Unicode characters outside that range will be escaped using either a
342single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence,
343as per RFC4627. The resulting encoded JSON text can be treated as a native
344Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string,
345or any other superset of ASCII.
346
347If C<$enable> is false, then the C<encode> method will not escape Unicode
348characters unless required by the JSON syntax or other flags. This results
349in a faster and more compact format.
350
351See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
352
353The main use for this flag is to produce JSON texts that can be
354transmitted over a 7-bit channel, as the encoded JSON texts will not
355contain any 8 bit characters.
356
357 JSON->new->ascii(1)->encode([chr 0x10401])
358 => ["\ud801\udc01"]
359
360=head2 latin1
361
362 $json = $json->latin1([$enable])
363
364 $enabled = $json->get_latin1
365
366If C<$enable> is true (or missing), then the C<encode> method will encode
367the resulting JSON text as latin1 (or iso-8859-1), escaping any characters
368outside the code range C<0..255>. The resulting string can be treated as a
369latin1-encoded JSON text or a native Unicode string. The C<decode> method
370will not be affected in any way by this flag, as C<decode> by default
371expects Unicode, which is a strict superset of latin1.
372
373If C<$enable> is false, then the C<encode> method will not escape Unicode
374characters unless required by the JSON syntax or other flags.
375
376See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
377
378The main use for this flag is efficiently encoding binary data as JSON
379text, as most octets will not be escaped, resulting in a smaller encoded
380size. The disadvantage is that the resulting JSON text is encoded
381in latin1 (and must correctly be treated as such when storing and
382transferring), a rare encoding for JSON. It is therefore most useful when
383you want to store data structures known to contain binary data efficiently
384in files or databases, not when talking to other JSON encoders/decoders.
385
386 JSON->new->latin1->encode (["\x{89}\x{abc}"]
387 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
388
389=head2 utf8
390
391 $json = $json->utf8([$enable])
392
393 $enabled = $json->get_utf8
394
395If C<$enable> is true (or missing), then the C<encode> method will encode
396the JSON result into UTF-8, as required by many protocols, while the
397C<decode> method expects to be handled an UTF-8-encoded string. Please
398note that UTF-8-encoded strings do not contain any characters outside the
399range C<0..255>, they are thus useful for bytewise/binary I/O. In future
400versions, enabling this option might enable autodetection of the UTF-16
401and UTF-32 encoding families, as described in RFC4627.
402
403If C<$enable> is false, then the C<encode> method will return the JSON
404string as a (non-encoded) Unicode string, while C<decode> expects thus a
405Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
406to be done yourself, e.g. using the Encode module.
407
408See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
409
410Example, output UTF-16BE-encoded JSON:
411
412 use Encode;
413 $jsontext = encode "UTF-16BE", JSON->new->encode ($object);
414
415Example, decode UTF-32LE-encoded JSON:
416
417 use Encode;
418 $object = JSON->new->decode (decode "UTF-32LE", $jsontext);
419
420=head2 pretty
421
422 $json = $json->pretty([$enable])
423
424This enables (or disables) all of the C<indent>, C<space_before> and
425C<space_after> (and in the future possibly more) flags in one call to
426generate the most readable (or most compact) form possible.
427
428=head2 indent
429
430 $json = $json->indent([$enable])
431
432 $enabled = $json->get_indent
433
434If C<$enable> is true (or missing), then the C<encode> method will use a multiline
435format as output, putting every array member or object/hash key-value pair
436into its own line, indenting them properly.
437
438If C<$enable> is false, no newlines or indenting will be produced, and the
439resulting JSON text is guaranteed not to contain any C<newlines>.
440
441This setting has no effect when decoding JSON texts.
442
443=head2 space_before
444
445 $json = $json->space_before([$enable])
446
447 $enabled = $json->get_space_before
448
449If C<$enable> is true (or missing), then the C<encode> method will add an extra
450optional space before the C<:> separating keys from values in JSON objects.
451
452If C<$enable> is false, then the C<encode> method will not add any extra
453space at those places.
454
455This setting has no effect when decoding JSON texts. You will also
456most likely combine this setting with C<space_after>.
457
458Example, space_before enabled, space_after and indent disabled:
459
460 {"key" :"value"}
461
462=head2 space_after
463
464 $json = $json->space_after([$enable])
465
466 $enabled = $json->get_space_after
467
468If C<$enable> is true (or missing), then the C<encode> method will add an extra
469optional space after the C<:> separating keys from values in JSON objects
470and extra whitespace after the C<,> separating key-value pairs and array
471members.
472
473If C<$enable> is false, then the C<encode> method will not add any extra
474space at those places.
475
476This setting has no effect when decoding JSON texts.
477
478Example, space_before and indent disabled, space_after enabled:
479
480 {"key": "value"}
481
482=head2 relaxed
483
484 $json = $json->relaxed([$enable])
485
486 $enabled = $json->get_relaxed
487
488If C<$enable> is true (or missing), then C<decode> will accept some
489extensions to normal JSON syntax (see below). C<encode> will not be
490affected in any way. I<Be aware that this option makes you accept invalid
491JSON texts as if they were valid!>. I suggest only to use this option to
492parse application-specific files written by humans (configuration files,
493resource files etc.)
494
495If C<$enable> is false (the default), then C<decode> will only accept
496valid JSON texts.
497
498Currently accepted extensions are:
499
500=over 4
501
502=item * list items can have an end-comma
503
504JSON I<separates> array elements and key-value pairs with commas. This
505can be annoying if you write JSON texts manually and want to be able to
506quickly append elements, so this extension accepts comma at the end of
507such items not just between them:
508
509 [
510 1,
511 2, <- this comma not normally allowed
512 ]
513 {
514 "k1": "v1",
515 "k2": "v2", <- this comma not normally allowed
516 }
517
518=item * shell-style '#'-comments
519
520Whenever JSON allows whitespace, shell-style comments are additionally
521allowed. They are terminated by the first carriage-return or line-feed
522character, after which more white-space and comments are allowed.
523
524 [
525 1, # this comment not allowed in JSON
526 # neither this one...
527 ]
528
529=back
530
531=head2 canonical
532
533 $json = $json->canonical([$enable])
534
535 $enabled = $json->get_canonical
536
537If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
538by sorting their keys. This is adding a comparatively high overhead.
539
540If C<$enable> is false, then the C<encode> method will output key-value
541pairs in the order Perl stores them (which will likely change between runs
542of the same script, and can change even within the same run from 5.18
543onwards).
544
545This option is useful if you want the same data structure to be encoded as
546the same JSON text (given the same overall settings). If it is disabled,
547the same hash might be encoded differently even if contains the same data,
548as key-value pairs have no inherent ordering in Perl.
549
550This setting has no effect when decoding JSON texts.
551
552This setting has currently no effect on tied hashes.
553
554=head2 allow_nonref
555
556 $json = $json->allow_nonref([$enable])
557
558 $enabled = $json->get_allow_nonref
559
560Unlike other boolean options, this option is enabled by default beginning
561with version C<4.0>.
562
563If C<$enable> is true (or missing), then the C<encode> method can convert a
564non-reference into its corresponding string, number or null JSON value,
565which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
566values instead of croaking.
567
568If C<$enable> is false, then the C<encode> method will croak if it isn't
569passed an arrayref or hashref, as JSON texts must either be an object
570or array. Likewise, C<decode> will croak if given something that is not a
571JSON object or array.
572
573Example, encode a Perl scalar as JSON value with enabled C<allow_nonref>,
574resulting in an invalid JSON text:
575
576 JSON->new->allow_nonref->encode ("Hello, World!")
577 => "Hello, World!"
578
579=head2 allow_unknown
580
581 $json = $json->allow_unknown ([$enable])
582
583 $enabled = $json->get_allow_unknown
584
585If C<$enable> is true (or missing), then C<encode> will I<not> throw an
586exception when it encounters values it cannot represent in JSON (for
587example, filehandles) but instead will encode a JSON C<null> value. Note
588that blessed objects are not included here and are handled separately by
589c<allow_blessed>.
590
591If C<$enable> is false (the default), then C<encode> will throw an
592exception when it encounters anything it cannot encode as JSON.
593
594This option does not affect C<decode> in any way, and it is recommended to
595leave it off unless you know your communications partner.
596
597=head2 allow_blessed
598
599 $json = $json->allow_blessed([$enable])
600
601 $enabled = $json->get_allow_blessed
602
603See L<OBJECT SERIALISATION> for details.
604
605If C<$enable> is true (or missing), then the C<encode> method will not
606barf when it encounters a blessed reference that it cannot convert
607otherwise. Instead, a JSON C<null> value is encoded instead of the object.
608
609If C<$enable> is false (the default), then C<encode> will throw an
610exception when it encounters a blessed object that it cannot convert
611otherwise.
612
613This setting has no effect on C<decode>.
614
615=head2 convert_blessed
616
617 $json = $json->convert_blessed([$enable])
618
619 $enabled = $json->get_convert_blessed
620
621See L<OBJECT SERIALISATION> for details.
622
623If C<$enable> is true (or missing), then C<encode>, upon encountering a
624blessed object, will check for the availability of the C<TO_JSON> method
625on the object's class. If found, it will be called in scalar context and
626the resulting scalar will be encoded instead of the object.
627
628The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
629returns other blessed objects, those will be handled in the same
630way. C<TO_JSON> must take care of not causing an endless recursion cycle
631(== crash) in this case. The name of C<TO_JSON> was chosen because other
632methods called by the Perl core (== not by the user of the object) are
633usually in upper case letters and to avoid collisions with any C<to_json>
634function or method.
635
636If C<$enable> is false (the default), then C<encode> will not consider
637this type of conversion.
638
639This setting has no effect on C<decode>.
640
641=head2 allow_tags (since version 3.0)
642
643 $json = $json->allow_tags([$enable])
644
645 $enabled = $json->get_allow_tags
646
647See L<OBJECT SERIALISATION> for details.
648
649If C<$enable> is true (or missing), then C<encode>, upon encountering a
650blessed object, will check for the availability of the C<FREEZE> method on
651the object's class. If found, it will be used to serialise the object into
652a nonstandard tagged JSON value (that JSON decoders cannot decode).
653
654It also causes C<decode> to parse such tagged JSON values and deserialise
655them via a call to the C<THAW> method.
656
657If C<$enable> is false (the default), then C<encode> will not consider
658this type of conversion, and tagged JSON values will cause a parse error
659in C<decode>, as if tags were not part of the grammar.
660
661=head2 boolean_values (since version 4.0)
662
663 $json->boolean_values([$false, $true])
664
665 ($false, $true) = $json->get_boolean_values
666
667By default, JSON booleans will be decoded as overloaded
668C<$JSON::false> and C<$JSON::true> objects.
669
670With this method you can specify your own boolean values for decoding -
671on decode, JSON C<false> will be decoded as a copy of C<$false>, and JSON
672C<true> will be decoded as C<$true> ("copy" here is the same thing as
673assigning a value to another variable, i.e. C<$copy = $false>).
674
675This is useful when you want to pass a decoded data structure directly
676to other serialisers like YAML, Data::MessagePack and so on.
677
678Note that this works only when you C<decode>. You can set incompatible
679boolean objects (like L<boolean>), but when you C<encode> a data structure
680with such boolean objects, you still need to enable C<convert_blessed>
681(and add a C<TO_JSON> method if necessary).
682
683Calling this method without any arguments will reset the booleans
684to their default values.
685
686C<get_boolean_values> will return both C<$false> and C<$true> values, or
687the empty list when they are set to the default.
688
689=head2 filter_json_object
690
691 $json = $json->filter_json_object([$coderef])
692
693When C<$coderef> is specified, it will be called from C<decode> each
694time it decodes a JSON object. The only argument is a reference to
695the newly-created hash. If the code references returns a single scalar
696(which need not be a reference), this value (or rather a copy of it) is
697inserted into the deserialised data structure. If it returns an empty
698list (NOTE: I<not> C<undef>, which is a valid scalar), the original
699deserialised hash will be inserted. This setting can slow down decoding
700considerably.
701
702When C<$coderef> is omitted or undefined, any existing callback will
703be removed and C<decode> will not change the deserialised hash in any
704way.
705
706Example, convert all JSON objects into the integer 5:
707
708 my $js = JSON->new->filter_json_object(sub { 5 });
709 # returns [5]
710 $js->decode('[{}]');
711 # returns 5
712 $js->decode('{"a":1, "b":2}');
713
714=head2 filter_json_single_key_object
715
716 $json = $json->filter_json_single_key_object($key [=> $coderef])
717
718Works remotely similar to C<filter_json_object>, but is only called for
719JSON objects having a single key named C<$key>.
720
721This C<$coderef> is called before the one specified via
722C<filter_json_object>, if any. It gets passed the single value in the JSON
723object. If it returns a single value, it will be inserted into the data
724structure. If it returns nothing (not even C<undef> but the empty list),
725the callback from C<filter_json_object> will be called next, as if no
726single-key callback were specified.
727
728If C<$coderef> is omitted or undefined, the corresponding callback will be
729disabled. There can only ever be one callback for a given key.
730
731As this callback gets called less often then the C<filter_json_object>
732one, decoding speed will not usually suffer as much. Therefore, single-key
733objects make excellent targets to serialise Perl objects into, especially
734as single-key JSON objects are as close to the type-tagged value concept
735as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
736support this in any way, so you need to make sure your data never looks
737like a serialised Perl hash.
738
739Typical names for the single object key are C<__class_whatever__>, or
740C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
741things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
742with real hashes.
743
744Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
745into the corresponding C<< $WIDGET{<id>} >> object:
746
747 # return whatever is in $WIDGET{5}:
748 JSON
749 ->new
750 ->filter_json_single_key_object (__widget__ => sub {
751 $WIDGET{ $_[0] }
752 })
753 ->decode ('{"__widget__": 5')
754
755 # this can be used with a TO_JSON method in some "widget" class
756 # for serialisation to json:
757 sub WidgetBase::TO_JSON {
758 my ($self) = @_;
759
760 unless ($self->{id}) {
761 $self->{id} = ..get..some..id..;
762 $WIDGET{$self->{id}} = $self;
763 }
764
765 { __widget__ => $self->{id} }
766 }
767
768=head2 max_depth
769
770 $json = $json->max_depth([$maximum_nesting_depth])
771
772 $max_depth = $json->get_max_depth
773
774Sets the maximum nesting level (default C<512>) accepted while encoding
775or decoding. If a higher nesting level is detected in JSON text or a Perl
776data structure, then the encoder and decoder will stop and croak at that
777point.
778
779Nesting level is defined by number of hash- or arrayrefs that the encoder
780needs to traverse to reach a given point or the number of C<{> or C<[>
781characters without their matching closing parenthesis crossed to reach a
782given character in a string.
783
784Setting the maximum depth to one disallows any nesting, so that ensures
785that the object is only a single hash/object or array.
786
787If no argument is given, the highest possible setting will be used, which
788is rarely useful.
789
790See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
791
792=head2 max_size
793
794 $json = $json->max_size([$maximum_string_size])
795
796 $max_size = $json->get_max_size
797
798Set the maximum length a JSON text may have (in bytes) where decoding is
799being attempted. The default is C<0>, meaning no limit. When C<decode>
800is called on a string that is longer then this many bytes, it will not
801attempt to decode the string but throw an exception. This setting has no
802effect on C<encode> (yet).
803
804If no argument is given, the limit check will be deactivated (same as when
805C<0> is specified).
806
807See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
808
809=head2 encode
810
811 $json_text = $json->encode($perl_scalar)
812
813Converts the given Perl value or data structure to its JSON
814representation. Croaks on error.
815
816=head2 decode
817
818 $perl_scalar = $json->decode($json_text)
819
820The opposite of C<encode>: expects a JSON text and tries to parse it,
821returning the resulting simple scalar or reference. Croaks on error.
822
823=head2 decode_prefix
824
825 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
826
827This works like the C<decode> method, but instead of raising an exception
828when there is trailing garbage after the first JSON object, it will
829silently stop parsing there and return the number of characters consumed
830so far.
831
832This is useful if your JSON texts are not delimited by an outer protocol
833and you need to know where the JSON text ends.
834
835 JSON->new->decode_prefix ("[1] the tail")
836 => ([1], 3)
837
838=head1 ADDITIONAL METHODS
839
840The following methods are for this module only.
841
842=head2 backend
843
844 $backend = $json->backend
845
846Since 2.92, C<backend> method returns an abstract backend module used currently,
847which should be JSON::Backend::XS (which inherits JSON::XS or Cpanel::JSON::XS),
848or JSON::Backend::PP (which inherits JSON::PP), not to monkey-patch the actual
849backend module globally.
850
851If you need to know what is used actually, use C<isa>, instead of string comparison.
852
853=head2 is_xs
854
855 $boolean = $json->is_xs
856
857Returns true if the backend inherits JSON::XS or Cpanel::JSON::XS.
858
859=head2 is_pp
860
861 $boolean = $json->is_pp
862
863Returns true if the backend inherits JSON::PP.
864
865=head2 property
866
867 $settings = $json->property()
868
869Returns a reference to a hash that holds all the common flag settings.
870
871 $json = $json->property('utf8' => 1)
872 $value = $json->property('utf8') # 1
873
874You can use this to get/set a value of a particular flag.
875
876=head2 boolean
877
878 $boolean_object = JSON->boolean($scalar)
879
880Returns $JSON::true if $scalar contains a true value, $JSON::false otherwise.
881You can use this as a full-qualified function (C<JSON::boolean($scalar)>).
882
883=head1 INCREMENTAL PARSING
884
885This section is also taken from JSON::XS.
886
887In some cases, there is the need for incremental parsing of JSON
888texts. While this module always has to keep both JSON text and resulting
889Perl data structure in memory at one time, it does allow you to parse a
890JSON stream incrementally. It does so by accumulating text until it has
891a full JSON object, which it then can decode. This process is similar to
892using C<decode_prefix> to see if a full JSON object is available, but
893is much more efficient (and can be implemented with a minimum of method
894calls).
895
896This module will only attempt to parse the JSON text once it is sure it
897has enough text to get a decisive result, using a very simple but
898truly incremental parser. This means that it sometimes won't stop as
899early as the full parser, for example, it doesn't detect mismatched
900parentheses. The only thing it guarantees is that it starts decoding as
901soon as a syntactically valid JSON text has been seen. This means you need
902to set resource limits (e.g. C<max_size>) to ensure the parser will stop
903parsing in the presence if syntax errors.
904
905The following methods implement this incremental parser.
906
907=head2 incr_parse
908
909 $json->incr_parse( [$string] ) # void context
910
911 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
912
913 @obj_or_empty = $json->incr_parse( [$string] ) # list context
914
915This is the central parsing function. It can both append new text and
916extract objects from the stream accumulated so far (both of these
917functions are optional).
918
919If C<$string> is given, then this string is appended to the already
920existing JSON fragment stored in the C<$json> object.
921
922After that, if the function is called in void context, it will simply
923return without doing anything further. This can be used to add more text
924in as many chunks as you want.
925
926If the method is called in scalar context, then it will try to extract
927exactly I<one> JSON object. If that is successful, it will return this
928object, otherwise it will return C<undef>. If there is a parse error,
929this method will croak just as C<decode> would do (one can then use
930C<incr_skip> to skip the erroneous part). This is the most common way of
931using the method.
932
933And finally, in list context, it will try to extract as many objects
934from the stream as it can find and return them, or the empty list
935otherwise. For this to work, there must be no separators (other than
936whitespace) between the JSON objects or arrays, instead they must be
937concatenated back-to-back. If an error occurs, an exception will be
938raised as in the scalar context case. Note that in this case, any
939previously-parsed JSON texts will be lost.
940
941Example: Parse some JSON arrays/objects in a given string and return
942them.
943
944 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
945
946=head2 incr_text
947
948 $lvalue_string = $json->incr_text
949
950This method returns the currently stored JSON fragment as an lvalue, that
951is, you can manipulate it. This I<only> works when a preceding call to
952C<incr_parse> in I<scalar context> successfully returned an object. Under
953all other circumstances you must not call this function (I mean it.
954although in simple tests it might actually work, it I<will> fail under
955real world conditions). As a special exception, you can also call this
956method before having parsed anything.
957
958That means you can only use this function to look at or manipulate text
959before or after complete JSON objects, not while the parser is in the
960middle of parsing a JSON object.
961
962This function is useful in two cases: a) finding the trailing text after a
963JSON object or b) parsing multiple JSON objects separated by non-JSON text
964(such as commas).
965
966=head2 incr_skip
967
968 $json->incr_skip
969
970This will reset the state of the incremental parser and will remove
971the parsed text from the input buffer so far. This is useful after
972C<incr_parse> died, in which case the input buffer and incremental parser
973state is left unchanged, to skip the text parsed so far and to reset the
974parse state.
975
976The difference to C<incr_reset> is that only text until the parse error
977occurred is removed.
978
979=head2 incr_reset
980
981 $json->incr_reset
982
983This completely resets the incremental parser, that is, after this call,
984it will be as if the parser had never parsed anything.
985
986This is useful if you want to repeatedly parse JSON objects and want to
987ignore any trailing data, which means you have to reset the parser after
988each successful decode.
989
990=head1 MAPPING
991
992Most of this section is also taken from JSON::XS.
993
994This section describes how the backend modules map Perl values to JSON values and
995vice versa. These mappings are designed to "do the right thing" in most
996circumstances automatically, preserving round-tripping characteristics
997(what you put in comes out as something equivalent).
998
999For the more enlightened: note that in the following descriptions,
1000lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl>
1001refers to the abstract Perl language itself.
1002
1003=head2 JSON -> PERL
1004
1005=over 4
1006
1007=item object
1008
1009A JSON object becomes a reference to a hash in Perl. No ordering of object
1010keys is preserved (JSON does not preserver object key ordering itself).
1011
1012=item array
1013
1014A JSON array becomes a reference to an array in Perl.
1015
1016=item string
1017
1018A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1019are represented by the same codepoints in the Perl string, so no manual
1020decoding is necessary.
1021
1022=item number
1023
1024A JSON number becomes either an integer, numeric (floating point) or
1025string scalar in perl, depending on its range and any fractional parts. On
1026the Perl level, there is no difference between those as Perl handles all
1027the conversion details, but an integer may take slightly less memory and
1028might represent more values exactly than floating point numbers.
1029
1030If the number consists of digits only, this module will try to represent
1031it as an integer value. If that fails, it will try to represent it as
1032a numeric (floating point) value if that is possible without loss of
1033precision. Otherwise it will preserve the number as a string value (in
1034which case you lose roundtripping ability, as the JSON number will be
1035re-encoded to a JSON string).
1036
1037Numbers containing a fractional or exponential part will always be
1038represented as numeric (floating point) values, possibly at a loss of
1039precision (in which case you might lose perfect roundtripping ability, but
1040the JSON number will still be re-encoded as a JSON number).
1041
1042Note that precision is not accuracy - binary floating point values cannot
1043represent most decimal fractions exactly, and when converting from and to
1044floating point, this module only guarantees precision up to but not including
1045the least significant bit.
1046
1047=item true, false
1048
1049These JSON atoms become C<JSON::true> and C<JSON::false>,
1050respectively. They are overloaded to act almost exactly like the numbers
1051C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
1052the C<JSON::is_bool> function.
1053
1054=item null
1055
1056A JSON null atom becomes C<undef> in Perl.
1057
1058=item shell-style comments (C<< # I<text> >>)
1059
1060As a nonstandard extension to the JSON syntax that is enabled by the
1061C<relaxed> setting, shell-style comments are allowed. They can start
1062anywhere outside strings and go till the end of the line.
1063
1064=item tagged values (C<< (I<tag>)I<value> >>).
1065
1066Another nonstandard extension to the JSON syntax, enabled with the
1067C<allow_tags> setting, are tagged values. In this implementation, the
1068I<tag> must be a perl package/class name encoded as a JSON string, and the
1069I<value> must be a JSON array encoding optional constructor arguments.
1070
1071See L<OBJECT SERIALISATION>, below, for details.
1072
1073=back
1074
1075
1076=head2 PERL -> JSON
1077
1078The mapping from Perl to JSON is slightly more difficult, as Perl is a
1079truly typeless language, so we can only guess which JSON type is meant by
1080a Perl value.
1081
1082=over 4
1083
1084=item hash references
1085
1086Perl hash references become JSON objects. As there is no inherent
1087ordering in hash keys (or JSON objects), they will usually be encoded
1088in a pseudo-random order. This module can optionally sort the hash keys
1089(determined by the I<canonical> flag), so the same data structure will
1090serialise to the same JSON text (given same settings and version of
1091the same backend), but this incurs a runtime overhead and is only rarely useful,
1092e.g. when you want to compare some JSON text against another for equality.
1093
1094=item array references
1095
1096Perl array references become JSON arrays.
1097
1098=item other references
1099
1100Other unblessed references are generally not allowed and will cause an
1101exception to be thrown, except for references to the integers C<0> and
1102C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1103also use C<JSON::false> and C<JSON::true> to improve readability.
1104
1105 encode_json [\0,JSON::true] # yields [false,true]
1106
1107=item JSON::true, JSON::false, JSON::null
1108
1109These special values become JSON true and JSON false values,
1110respectively. You can also use C<\1> and C<\0> directly if you want.
1111
1112=item blessed objects
1113
1114Blessed objects are not directly representable in JSON, but C<JSON::XS>
1115allows various ways of handling objects. See L<OBJECT SERIALISATION>,
1116below, for details.
1117
1118=item simple scalars
1119
1120Simple Perl scalars (any scalar that is not a reference) are the most
1121difficult objects to encode: this module will encode undefined scalars as
1122JSON C<null> values, scalars that have last been used in a string context
1123before encoding as JSON strings, and anything else as number value:
1124
1125 # dump as number
1126 encode_json [2] # yields [2]
1127 encode_json [-3.0e17] # yields [-3e+17]
1128 my $value = 5; encode_json [$value] # yields [5]
1129
1130 # used as string, so dump as string
1131 print $value;
1132 encode_json [$value] # yields ["5"]
1133
1134 # undef becomes null
1135 encode_json [undef] # yields [null]
1136
1137You can force the type to be a string by stringifying it:
1138
1139 my $x = 3.1; # some variable containing a number
1140 "$x"; # stringified
1141 $x .= ""; # another, more awkward way to stringify
1142 print $x; # perl does it for you, too, quite often
1143
1144You can force the type to be a number by numifying it:
1145
1146 my $x = "3"; # some variable containing a string
1147 $x += 0; # numify it, ensuring it will be dumped as a number
1148 $x *= 1; # same thing, the choice is yours.
1149
1150You can not currently force the type in other, less obscure, ways. Tell me
1151if you need this capability (but don't forget to explain why it's needed
1152:).
1153
1154Since version 2.91_01, JSON::PP uses a different number detection logic
1155that converts a scalar that is possible to turn into a number safely.
1156The new logic is slightly faster, and tends to help people who use older
1157perl or who want to encode complicated data structure. However, this may
1158results in a different JSON text from the one JSON::XS encodes (and
1159thus may break tests that compare entire JSON texts). If you do
1160need the previous behavior for better compatibility or for finer control,
1161set PERL_JSON_PP_USE_B environmental variable to true before you
1162C<use> JSON.
1163
1164Note that numerical precision has the same meaning as under Perl (so
1165binary to decimal conversion follows the same rules as in Perl, which
1166can differ to other languages). Also, your perl interpreter might expose
1167extensions to the floating point numbers of your platform, such as
1168infinities or NaN's - these cannot be represented in JSON, and it is an
1169error to pass those in.
1170
1171JSON.pm backend modules trust what you pass to C<encode> method
1172(or C<encode_json> function) is a clean, validated data structure with
1173values that can be represented as valid JSON values only, because it's
1174not from an external data source (as opposed to JSON texts you pass to
1175C<decode> or C<decode_json>, which JSON backends consider tainted and
1176don't trust). As JSON backends don't know exactly what you and consumers
1177of your JSON texts want the unexpected values to be (you may want to
1178convert them into null, or to stringify them with or without
1179normalisation (string representation of infinities/NaN may vary
1180depending on platforms), or to croak without conversion), you're advised
1181to do what you and your consumers need before you encode, and also not
1182to numify values that may start with values that look like a number
1183(including infinities/NaN), without validating.
1184
1185=back
1186
1187=head2 OBJECT SERIALISATION
1188
1189As JSON cannot directly represent Perl objects, you have to choose between
1190a pure JSON representation (without the ability to deserialise the object
1191automatically again), and a nonstandard extension to the JSON syntax,
1192tagged values.
1193
1194=head3 SERIALISATION
1195
1196What happens when this module encounters a Perl object depends on the
1197C<allow_blessed>, C<convert_blessed> and C<allow_tags> settings, which
1198are used in this order:
1199
1200=over 4
1201
1202=item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method.
1203
1204In this case, C<JSON> creates a tagged JSON value, using a nonstandard
1205extension to the JSON syntax.
1206
1207This works by invoking the C<FREEZE> method on the object, with the first
1208argument being the object to serialise, and the second argument being the
1209constant string C<JSON> to distinguish it from other serialisers.
1210
1211The C<FREEZE> method can return any number of values (i.e. zero or
1212more). These values and the package/classname of the object will then be
1213encoded as a tagged JSON value in the following format:
1214
1215 ("classname")[FREEZE return values...]
1216
1217e.g.:
1218
1219 ("URI")["http://www.google.com/"]
1220 ("MyDate")[2013,10,29]
1221 ("ImageData::JPEG")["Z3...VlCg=="]
1222
1223For example, the hypothetical C<My::Object> C<FREEZE> method might use the
1224objects C<type> and C<id> members to encode the object:
1225
1226 sub My::Object::FREEZE {
1227 my ($self, $serialiser) = @_;
1228
1229 ($self->{type}, $self->{id})
1230 }
1231
1232=item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method.
1233
1234In this case, the C<TO_JSON> method of the object is invoked in scalar
1235context. It must return a single scalar that can be directly encoded into
1236JSON. This scalar replaces the object in the JSON text.
1237
1238For example, the following C<TO_JSON> method will convert all L<URI>
1239objects to JSON strings when serialised. The fact that these values
1240originally were L<URI> objects is lost.
1241
1242 sub URI::TO_JSON {
1243 my ($uri) = @_;
1244 $uri->as_string
1245 }
1246
1247=item 3. C<allow_blessed> is enabled.
1248
1249The object will be serialised as a JSON null value.
1250
1251=item 4. none of the above
1252
1253If none of the settings are enabled or the respective methods are missing,
1254this module throws an exception.
1255
1256=back
1257
1258=head3 DESERIALISATION
1259
1260For deserialisation there are only two cases to consider: either
1261nonstandard tagging was used, in which case C<allow_tags> decides,
1262or objects cannot be automatically be deserialised, in which
1263case you can use postprocessing or the C<filter_json_object> or
1264C<filter_json_single_key_object> callbacks to get some real objects our of
1265your JSON.
1266
1267This section only considers the tagged value case: a tagged JSON object
1268is encountered during decoding and C<allow_tags> is disabled, a parse
1269error will result (as if tagged values were not part of the grammar).
1270
1271If C<allow_tags> is enabled, this module will look up the C<THAW> method
1272of the package/classname used during serialisation (it will not attempt
1273to load the package as a Perl module). If there is no such method, the
1274decoding will fail with an error.
1275
1276Otherwise, the C<THAW> method is invoked with the classname as first
1277argument, the constant string C<JSON> as second argument, and all the
1278values from the JSON array (the values originally returned by the
1279C<FREEZE> method) as remaining arguments.
1280
1281The method must then return the object. While technically you can return
1282any Perl scalar, you might have to enable the C<allow_nonref> setting to
1283make that work in all cases, so better return an actual blessed reference.
1284
1285As an example, let's implement a C<THAW> function that regenerates the
1286C<My::Object> from the C<FREEZE> example earlier:
1287
1288 sub My::Object::THAW {
1289 my ($class, $serialiser, $type, $id) = @_;
1290
1291 $class->new (type => $type, id => $id)
1292 }
1293
1294
1295=head1 ENCODING/CODESET FLAG NOTES
1296
1297This section is taken from JSON::XS.
1298
1299The interested reader might have seen a number of flags that signify
1300encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be
1301some confusion on what these do, so here is a short comparison:
1302
1303C<utf8> controls whether the JSON text created by C<encode> (and expected
1304by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only
1305control whether C<encode> escapes character values outside their respective
1306codeset range. Neither of these flags conflict with each other, although
1307some combinations make less sense than others.
1308
1309Care has been taken to make all flags symmetrical with respect to
1310C<encode> and C<decode>, that is, texts encoded with any combination of
1311these flag values will be correctly decoded when the same flags are used
1312- in general, if you use different flag settings while encoding vs. when
1313decoding you likely have a bug somewhere.
1314
1315Below comes a verbose discussion of these flags. Note that a "codeset" is
1316simply an abstract set of character-codepoint pairs, while an encoding
1317takes those codepoint numbers and I<encodes> them, in our case into
1318octets. Unicode is (among other things) a codeset, UTF-8 is an encoding,
1319and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at
1320the same time, which can be confusing.
1321
1322=over 4
1323
1324=item C<utf8> flag disabled
1325
1326When C<utf8> is disabled (the default), then C<encode>/C<decode> generate
1327and expect Unicode strings, that is, characters with high ordinal Unicode
1328values (> 255) will be encoded as such characters, and likewise such
1329characters are decoded as-is, no changes to them will be done, except
1330"(re-)interpreting" them as Unicode codepoints or Unicode characters,
1331respectively (to Perl, these are the same thing in strings unless you do
1332funny/weird/dumb stuff).
1333
1334This is useful when you want to do the encoding yourself (e.g. when you
1335want to have UTF-16 encoded JSON texts) or when some other layer does
1336the encoding for you (for example, when printing to a terminal using a
1337filehandle that transparently encodes to UTF-8 you certainly do NOT want
1338to UTF-8 encode your data first and have Perl encode it another time).
1339
1340=item C<utf8> flag enabled
1341
1342If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all
1343characters using the corresponding UTF-8 multi-byte sequence, and will
1344expect your input strings to be encoded as UTF-8, that is, no "character"
1345of the input string must have any value > 255, as UTF-8 does not allow
1346that.
1347
1348The C<utf8> flag therefore switches between two modes: disabled means you
1349will get a Unicode string in Perl, enabled means you get an UTF-8 encoded
1350octet/binary string in Perl.
1351
1352=item C<latin1> or C<ascii> flags enabled
1353
1354With C<latin1> (or C<ascii>) enabled, C<encode> will escape characters
1355with ordinal values > 255 (> 127 with C<ascii>) and encode the remaining
1356characters as specified by the C<utf8> flag.
1357
1358If C<utf8> is disabled, then the result is also correctly encoded in those
1359character sets (as both are proper subsets of Unicode, meaning that a
1360Unicode string with all character values < 256 is the same thing as a
1361ISO-8859-1 string, and a Unicode string with all character values < 128 is
1362the same thing as an ASCII string in Perl).
1363
1364If C<utf8> is enabled, you still get a correct UTF-8-encoded string,
1365regardless of these flags, just some more characters will be escaped using
1366C<\uXXXX> then before.
1367
1368Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8
1369encoding, while ASCII-encoded strings are. That is because the ISO-8859-1
1370encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being
1371a subset of Unicode), while ASCII is.
1372
1373Surprisingly, C<decode> will ignore these flags and so treat all input
1374values as governed by the C<utf8> flag. If it is disabled, this allows you
1375to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of
1376Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.
1377
1378So neither C<latin1> nor C<ascii> are incompatible with the C<utf8> flag -
1379they only govern when the JSON output engine escapes a character or not.
1380
1381The main use for C<latin1> is to relatively efficiently store binary data
1382as JSON, at the expense of breaking compatibility with most JSON decoders.
1383
1384The main use for C<ascii> is to force the output to not contain characters
1385with values > 127, which means you can interpret the resulting string
1386as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and
13878-bit-encoding, and still get the same data structure back. This is useful
1388when your channel for JSON transfer is not 8-bit clean or the encoding
1389might be mangled in between (e.g. in mail), and works because ASCII is a
1390proper subset of most 8-bit and multibyte encodings in use in the world.
1391
1392=back
1393
1394=head1 BACKWARD INCOMPATIBILITY
1395
1396Since version 2.90, stringification (and string comparison) for
1397C<JSON::true> and C<JSON::false> has not been overloaded. It shouldn't
1398matter as long as you treat them as boolean values, but a code that
1399expects they are stringified as "true" or "false" doesn't work as
1400you have expected any more.
1401
1402 if (JSON::true eq 'true') { # now fails
1403
1404 print "The result is $JSON::true now."; # => The result is 1 now.
1405
1406And now these boolean values don't inherit JSON::Boolean, either.
1407When you need to test a value is a JSON boolean value or not, use
1408C<JSON::is_bool> function, instead of testing the value inherits
1409a particular boolean class or not.
1410
1411=head1 BUGS
1412
1413Please report bugs on backend selection and additional features
1414this module provides to RT or GitHub issues for this module:
1415
1416L<https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON>
1417
1418L<https://github.com/makamaka/JSON/issues>
1419
1420As for bugs on a specific behavior, please report to the author
1421of the backend module you are using.
1422
1423As for new features and requests to change common behaviors, please
1424ask the author of JSON::XS (Marc Lehmann, E<lt>schmorp[at]schmorp.deE<gt>)
1425first, by email (important!), to keep compatibility among JSON.pm
1426backends.
1427
1428=head1 SEE ALSO
1429
1430L<JSON::XS>, L<Cpanel::JSON::XS>, L<JSON::PP> for backends.
1431
1432L<JSON::MaybeXS>, an alternative that prefers Cpanel::JSON::XS.
1433
1434C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
1435
1436RFC7159 (L<http://www.ietf.org/rfc/rfc7159.txt>)
1437
1438RFC8259 (L<http://www.ietf.org/rfc/rfc8259.txt>)
1439
1440=head1 AUTHOR
1441
1442Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
1443
1444JSON::XS was written by Marc Lehmann E<lt>schmorp[at]schmorp.deE<gt>
1445
1446The release of this new version owes to the courtesy of Marc Lehmann.
1447
1448=head1 CURRENT MAINTAINER
1449
1450Kenichi Ishigaki, E<lt>ishigaki[at]cpan.orgE<gt>
1451
1452=head1 COPYRIGHT AND LICENSE
1453
1454Copyright 2005-2013 by Makamaka Hannyaharamitu
1455
1456Most of the documentation is taken from JSON::XS by Marc Lehmann
1457
1458This library is free software; you can redistribute it and/or modify
1459it under the same terms as Perl itself.
1460
1461=cut
1462
1463
1464;